import Taro from "@tarojs/taro"

type iconType = "none" | "success" | "error" | "loading" | undefined

const tarBarPages = ['pages/home/index', 'pages/order/index', 'pages/mine/index']

const ShowToast = (title, icon = 'none', duration = 1500) => {
	return new Promise((resolve) => {
		Taro.showToast({
			title,
			duration,
			icon: icon as iconType,
			mask: true
		})
		setTimeout(() => {
			resolve(true)
		}, duration)
	})
}
const ShowFail = (title = "失败") => {
	return ShowToast(title, 'error')
}

const ShowLoading = (title = "请稍候", mask = true) => {
	return Taro.showLoading({
		title,
		mask
	})
}

const HideLoading = () => {
	Taro.hideLoading()
}

const ToPage = (path, isReplace = false) => {
	if (tarBarPages.some(url => {
		return path?.includes(url)
	})) {
		Taro.switchTab({url: path.split('?')[0]})
	} else {
		if (isReplace) {
			Taro.redirectTo({url: path})
		} else {
			Taro.navigateTo({url: path})
		}
	}
}


const requestAllowNotice = () => {
	if (process.env.NODE_ENV !== 'development') {
		Taro.requestSubscribeMessage({
			tmplIds: ['sVAHeMtfha1SkZJRSdjwKUCeHpkMLIhIbKpVrF_nlPQ'],
			entityIds: [],
			success: () => {
				console.log('消息授权成功');
			},
			fail: () => {
				console.log('消息授权失败');
			}
		})
	}
}

const VibrateShort = (() => {
	return () => {
		Taro.vibrateShort()
		// 在操作时询问消息接收
		requestAllowNotice()
	}
})()

const uuid = () => {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8)
		return v.toString(16)
	})
}

export {
	tarBarPages,
	ShowToast,
	ShowFail,
	ShowLoading,
	HideLoading,
	ToPage,
	VibrateShort,
	uuid
}